//
//  DataPointManager.m
//  Peso Guide
//
//  Created by macbook on 2025/6/21.
//

#import "DataPointManager.h"
#import <CoreLocation/CoreLocation.h>
#import <AFNetworking/AFNetworking.h>

// 定位缓存有效期（10分钟）
static const NSTimeInterval kLocationCacheExpiration = 5;

@interface DataPointManager () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *cachedLocation;
@property (nonatomic, assign) NSTimeInterval lastLocationTimestamp;
@property (nonatomic, assign) BOOL isRequestingLocation;
@property (nonatomic, strong) NSMutableArray *pendingEvents; // 待处理事件队列

@end

@implementation DataPointManager

+ (instancetype)sharedManager {
    static DataPointManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DataPointManager alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _pendingEvents = [NSMutableArray array];
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    }
    return self;
}

// 获取当前秒级时间戳
+ (NSTimeInterval)currentTimestamp {
    return [[NSDate date] timeIntervalSince1970];
}

// 获取当前秒级时间戳
+ (NSString *)getCurrentTimestamp {
    NSString *timeStr = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    return timeStr;
}

- (void)logEventWithType:(NSString *)type startTime:(NSString *)startTime endTime:(NSString *)endTime orderId:(NSString *)orderId {
    
    if ([AppTools isEmpty:type]) {
        type = @"";
    }
    if ([AppTools isEmpty:startTime]) {
        startTime = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    }
    if ([AppTools isEmpty:endTime]) {
        endTime = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    }
    if ([AppTools isEmpty:orderId]) {
        orderId = @"";
    }
    
    NSDictionary *event = @{
        @"type": type,
        @"start_time": startTime,
        @"end_time": endTime,
        @"orderId": orderId
    };
    
    // 检查是否有有效的位置缓存
    if ([self isCachedLocationValid]) {
        [self sendEvent:event withLocation:self.cachedLocation];
    } else {
        @synchronized (self.pendingEvents) {
            [self.pendingEvents insertObject:event atIndex:0];
        }
        
        // 如果没有正在请求定位，则开始新请求
        if (!self.isRequestingLocation) {
            [self requestLocation];
        }
    }
}

- (BOOL)isCachedLocationValid {
    if (!self.cachedLocation) return NO;
    
    NSTimeInterval currentTime = [DataPointManager currentTimestamp];
    return (currentTime - self.lastLocationTimestamp) <= kLocationCacheExpiration;
}

- (void)requestLocation {
    self.isRequestingLocation = YES;
    
    // 检查权限状态
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        [self handleLocationFailure];
        return;
    }
    
    // 请求权限（如果未确定）
    if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    } else {
        [self.locationManager requestLocation];
    }
}

- (void)handleLocationFailure {
    // 使用 (0,0) 作为位置并处理所有待处理事件
    CLLocation *nullLocation = [[CLLocation alloc] initWithLatitude:0 longitude:0];
    self.cachedLocation = nullLocation;
    self.lastLocationTimestamp = [DataPointManager currentTimestamp];
    
    [self processPendingEventsWithLocation:nullLocation];
    self.isRequestingLocation = NO;
}

- (void)processPendingEventsWithLocation:(CLLocation *)location {
    NSArray *eventsToProcess;
    @synchronized (self.pendingEvents) {
        eventsToProcess = [self.pendingEvents copy];
        [self.pendingEvents removeAllObjects];
    }
    
    for (NSDictionary *event in eventsToProcess) {
        [self sendEvent:event withLocation:location];
    }
}

- (void)senRequestWithType:(NSString *)type startTime:(NSString *)startTime endTime:(NSString *)endTime lng:(NSString *)lng lat:(NSString *)lat orderId:(NSString *)orderId {
    
    if ([AppTools isEmpty:type]) {
        type = @"";
    }
    if ([AppTools isEmpty:startTime]) {
        startTime = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    }
    if ([AppTools isEmpty:endTime]) {
        endTime = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    }
    if ([AppTools isEmpty:lng]) {
        lng = @"";
    }
    if ([AppTools isEmpty:lat]) {
        lat = @"";
    }
    if ([AppTools isEmpty:orderId]) {
        orderId = @"";
    }
    
    // 构造请求参数
    NSDictionary *params = @{
        @"faster":type,
        @"strategy":@"2",
        @"shallow":[AppTools getOrCreatePseudoIDFV],
        @"whenever":[AppTools getIDFA],
        @"search": lng,
        @"care": lat,
        @"pushed": startTime,
        @"pairs": endTime,
        @"efficient":orderId
    };
    
    [[AWHttpService service] postWithUrl:@"/trains/desire" params:params succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            DLog(@"maidianfasong---chenggong");
        }else {
            DLog(@"maidianfasong---shibai");
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        DLog(@"maidianfasong---shibai");
    }];
}

- (void)sendEvent:(NSDictionary *)event withLocation:(CLLocation *)location {
    NSString *type = [NSString stringWithFormat:@"%@",event[@"type"]];
    NSString *startTime = [NSString stringWithFormat:@"%@",event[@"start_time"]];
    NSString *endTime = [NSString stringWithFormat:@"%@",event[@"end_time"]];
    NSString *orderId = [NSString stringWithFormat:@"%@",event[@"orderId"]];

    CLLocationCoordinate2D coordinate = location.coordinate;
    
    // 构造请求参数
    NSDictionary *params = @{
        @"faster":type,
        @"strategy":@"2",
        @"shallow":[AppTools getOrCreatePseudoIDFV],
        @"whenever":[AppTools getIDFA],
        @"search": [NSString stringWithFormat:@"%f",coordinate.longitude],
        @"care": [NSString stringWithFormat:@"%f",coordinate.latitude],
        @"pushed": startTime,
        @"pairs": endTime,
        @"efficient":orderId
    };
    
    [[AWHttpService service] postWithUrl:@"/trains/desire" params:params succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            DLog(@"maidianfasong---chenggong");
        }else {
            DLog(@"maidianfasong---shibai");
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        DLog(@"maidianfasong---shibai");
    }];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    if (locations.count > 0) {
        self.cachedLocation = [locations lastObject];
        self.lastLocationTimestamp = [DataPointManager currentTimestamp];
        [self processPendingEventsWithLocation:self.cachedLocation];
    }
    self.isRequestingLocation = NO;
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self handleLocationFailure];
}

- (void)locationManagerDidChangeAuthorization:(CLLocationManager *)manager {
    if (@available(iOS 14.0, *)) {
        if (manager.authorizationStatus == kCLAuthorizationStatusAuthorizedWhenInUse ||
            manager.authorizationStatus == kCLAuthorizationStatusAuthorizedAlways) {
            [self requestLocation];
        } else if (manager.authorizationStatus == kCLAuthorizationStatusDenied) {
            [self handleLocationFailure];
        }
    }
}

@end
